package com.fang.gateway.config;

import com.fang.common.common.CommonConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

/**
 * @Description
 * @Author Bernie_fang
 * @Date 2025/5/27 22:24
 **/
@Configuration
public class FeignTraceInterceptor implements RequestInterceptor {

//    @Override
//    public void apply(RequestTemplate template) {
//        String traceId = MDC.get(CommonConstants.CommonRequest.TRACE_ID);
//        if (traceId != null) {
//            template.header(CommonConstants.CommonRequest.TRACE_ID, traceId);
//            template.header(CommonConstants.CommonRequest.TRACE_ID_HEADER, traceId);
//        }
//    }
    @Override
    public void apply(RequestTemplate template) {
        Mono.deferContextual(ctx -> {
            String traceId = ctx.getOrDefault(CommonConstants.CommonRequest.TRACE_ID, "");
            template.header(CommonConstants.CommonRequest.TRACE_ID, traceId);
            template.header(CommonConstants.CommonRequest.TRACE_ID_HEADER, traceId);
            return Mono.empty();
        }).subscribe(); // 触发上下文读取
    }
}
/*
若服务内部使用异步线程（如@Async），默认情况下MDC不会跨线程传递，需手动复制。
自定义TaskDecorator

import org.slf4j.MDC;
import org.springframework.core.task.TaskDecorator;
import java.util.Map;

public class MdcTaskDecorator implements TaskDecorator {

    @Override
    public Runnable decorate(Runnable runnable) {
        Map<String, String> contextMap = MDC.getCopyOfContextMap();
        return () -> {
            try {
                if (contextMap != null) {
                    MDC.setContextMap(contextMap);
                }
                runnable.run();
            } finally {
                MDC.clear();
            }
        };
    }
}
注册到线程池：
@Bean
public Executor asyncExecutor() {
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    executor.setTaskDecorator(new MdcTaskDecorator());
    executor.initialize();
    return executor;
}
 */